package cadtoolbox.utils;

import java.util.LinkedHashSet;

import javax.swing.JFrame;
import javax.swing.JProgressBar;
import javax.swing.ProgressMonitor;
import javax.swing.SwingWorker;

import model.Constants;

import org.apache.commons.math3.ode.sampling.StepHandler;
import org.apache.commons.math3.ode.sampling.StepInterpolator;

public class MyStepHandler implements StepHandler {

	private double[][] timeSerie;
	private int time = 0;
	private PluggableWorker worker;
	
	
	@Override
	public void handleStep(StepInterpolator step, boolean isLastStep) {
		StepInterpolator localCopy = step.copy();
		if(step.getCurrentTime()>=time+1 && time<Constants.numberOfPoints-1){
			//while(time<step.getCurrentTime()&& time<Constants.numberOfPoints-1){
				time++;
				if(worker != null){
				worker.setCustomProgress((100*time)/Constants.numberOfPoints);
				}
				//worker.firePropertyChange("progress", time-1, time);
				
				//Thread.yield();
				//prog.setValue(time);
				//prog.repaint();
				//monitor.repaint();
				localCopy.setInterpolatedTime(time);
				//System.out.println("Time "+time);
				double[] y0 = localCopy.getInterpolatedState();
				for(int i=0;i<y0.length;i++){
					this.timeSerie[i][time]=y0[i];
				}
			//}
		}

	}

	@Override
	public void init(double t0, double[] y0, double t) {
		// Be careful that this is only valid if the init is done for time t=0
		this.timeSerie = new double[y0.length][Constants.numberOfPoints];
		//System.out.println(Math.min(sizeSimpleSeq,y0.length));
		for(int i=0;i<y0.length;i++){
			this.timeSerie[i][0]=y0[i];
		}
	}

	public double[][] getTimeSerie(){
		return this.timeSerie.clone();
	}
	
	public void registerWorker(PluggableWorker worker){
		this.worker = worker;
		//this.worker.setCustomProgress(0);
	}
}
